import {createRouter, createWebHashHistory} from 'vue-router'
import store from '../store/index'

const whiteList = ['/login']
const routes = [
  {
    path: '/login',
    component: () => import('../views/common/login.vue'),
    meta: {
      title: '登录'
    }
  },
  {
    path: '/',
    component: () => import('../views/index.vue'),
    meta: {
      title: '主页'
    },
    children: [{
      path: '',
      component: () => import('../views/welcome.vue'),
    }]
  },
]
const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

/**
 * 全局前置守卫
 */
router.beforeEach(async (to, from, next) => {
  document.title = to.meta.title || 'admin'
  // console.log(to, from)

  if (whiteList.includes(to.path)) {
    next()
    return true
  }
  const code = await checkLogin()
  if (code === 1) {
    next({path: '/login'})
    return true
  } else if (code === 2) {
    next({path: to.path})
    return true
  }
  next()
})

/**
 * 检查登录
 * @return {Promise<number>}
 */
async function checkLogin() {
  // 是否登录
  const token = sessionStorage.getItem('token')
  if (!token)
    return 1
  // 当前用户
  const loginUser = store.state.user.loginUser
  if (!loginUser) {
    await store.dispatch('getLoginUser')
    if (!store.state.user.loginUser)
      return 1
  }
  // 用户资源
  let resources = store.state.user.resources
  if (!resources) {
    await store.dispatch('getResources')
    resources = store.state.user.resources
    if (!resources)
      return 1
    getRoutes(resources, 1)?.forEach(v => router.addRoute(v))
    // console.log(router.getRoutes())
    // getRoutes2(resources)
    return 2
  }
  return 0
}

/**
 * 将资源转化为路由
 * @param resources
 */
function getRoutes(resources, level) {
  if (!resources)
    return null
  level++
  return resources.map(v => {
    let component = () => import(`../views/index.vue`)
    if (!v.children)
      component = () => import(`../views${v.path}.vue`)
    else if (level != 2)
      component = () => import(`../views/common/middle.vue`)
    return {
      name: v.id,
      path: v.path,
      component,
      meta: {
        title: v.name
      },
      children: getRoutes(v.children, level)
    }
  })
}

export default router
